//
//  XMPublishViewController.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/7/2.
//

#import "XMPublishViewController.h"
#import "XMPublishView.h"
#import "XMMyAddressViewController.h"
#import "XMNetwork+publish.h"
#import "XMServiceModel.h"
#import "XMNetwork+mine.h"
#import <Photos/Photos.h>
#import <CoreLocation/CoreLocation.h>

@interface XMPublishViewController ()<XMPublishViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) XMPublishView *publishView;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

@end

@implementation XMPublishViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationBar:YES animated:YES];
    [self.locationManager startUpdatingLocation];
    if (_publishView) {
        [self.view addSubview:_publishView];
        [_publishView show];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
        
    }];
    [self creatUI];
}

- (void)creatUI {
    [self.view addSubview:self.publishView];
    [_publishView show];
    [self getServiceType];
    if (_serviceId && _serviceId.length > 0) {
        [self getMeetingModel];
    }
}

//见面详情
- (void)getMeetingModel {
    XMWeakSelf;
    [_Network getMeetingDetailWithServiceId:_serviceId
                                    success:^(id  _Nonnull responseObject) {
        XMMeetingDetailModel *detailModel = [XMMeetingDetailModel yy_modelWithJSON:responseObject[@"data"]];
        [weakSelf.publishView setcontentwithMeetingModel:detailModel];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//见面类型
- (void)getServiceType {
    XMWeakSelf;
    [_Network getMeetingSceneSuccess:^(id  _Nonnull responseObject) {
        NSArray *serviceModelArr = [NSArray yy_modelArrayWithClass:[XMServiceModel class] json:responseObject[@"data"]];
        [weakSelf.publishView setContentWithServiceModelArr:serviceModelArr];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//发布
- (void)publishWithParameters:(NSMutableDictionary *)parameters {
    if (_serviceId && _serviceId.length > 0) {
        [parameters safe_setObject:_serviceId forKey:@"id"];
    }
    if (_coordinate.latitude != 0) {
        [parameters safe_setObject:[NSString stringWithFormat:@"%f,%f", _coordinate.longitude, _coordinate.latitude] forKey:@"addrPoint"];
    }
    XMWeakSelf;
    [_Network publishMeetingWithParameters:parameters
                                   success:^(id  _Nonnull responseObject) {
        [MBProgressHUD showSuccess:@"保存成功"];
        self.saveSuccessBlock ? self.saveSuccessBlock() : nil;
        [weakSelf.publishView saveSuccess];
        if (weakSelf.navigationController.viewControllers.count > 1) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//上传图片
- (void)upLoadFileWithFileType:(NSString *)fileType
                           img:(UIImage *)selectImg
                       fileUrl:(NSURL *)fileUrl {
//    [self.publishView setSelectImg:selectImg];
    XMWeakSelf;
    [_Network updateAvatarWithImg:selectImg
                          success:^(id  _Nonnull repsonseObject) {
        NSString *avatarStr = [repsonseObject safeStringForKey:@"data"];
        [weakSelf.publishView setSelectImg:avatarStr];
    } failure:^(NSError * _Nonnull error) {

    }];
}

#pragma mark - Delegate
- (void)backAction {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.saveSuccessBlock ? self.saveSuccessBlock() : nil;
    }
}

//地址选择
- (void)positionSelectAction {
    XMMyAddressViewController *myAddressVC = [[XMMyAddressViewController alloc] init];
    myAddressVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:myAddressVC animated:YES];
    XMWeakSelf;
    myAddressVC.addressModelSelectBlock = ^(XMAddressModel * _Nonnull addressModel) {
        [weakSelf.publishView setContentWithAddressModel:addressModel];
    };
}

//上传图片
- (void)upLoadImg {
    XMWeakSelf;
    UIAlertController *alertVC = [UIAlertController initwithTitle:@"选择图片"
                                                          message:@""
                                                           titles:@[@"相册", @"相机"]
                                                      cancelTitle:@"取消"
                                                       alertStyle:UIAlertControllerStyleActionSheet
                                                       itemSelect:^(NSInteger selectIndex) {
        if (selectIndex == 0) {
            [weakSelf selectImgFromLibrary];
        }
        else {
            [weakSelf selectImgFromCamera];
        }
    }];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)selectImgFromLibrary {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerVC.delegate = self;
        pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }
    else {
        [MBProgressHUD showError:@"无相册权限"];
    }
}

- (void)selectImgFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        pickerVC.delegate = self;
        pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }
    else {
        [MBProgressHUD showError:@"无相册权限"];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//    NSURL *fileUrl = [info objectForKey:UIImagePickerControllerImageURL];
    if ([mediaType containsString:@"image"]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self upLoadFileWithFileType:@"1" img:img fileUrl:nil];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations firstObject];
    _coordinate = location.coordinate;
    [manager stopUpdatingLocation];
}

#pragma mark - Init
- (XMPublishView *)publishView {
    if (!_publishView) {
        _publishView = [[XMPublishView alloc] initWithFrame:self.view.bounds];
        _publishView.delegate = self;
    }
    return _publishView;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 1000.0f;
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];
    }
    return _locationManager;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
